<?php

namespace mpend\modules\notice\models;

use common\components\wechat\MpWechat;
use common\models\notice\NoticeAttach;
use common\models\notice\NoticeNeed;
use common\models\notice\ShowbizRole;
use Yii;
use common\base\Model;
use common\models\user\User;
use common\helpers\Url;
use common\models\notice\Notice;
use yii\db\Exception;

class NoticeForm extends Model
{
    /**
     * @var 通告ID
     */
    public $notice_id;

    /**
     * @var 登录用户ID
     */
    public $user_id;

    /**
     * 标题
     */
    public $title;

    /**
     * 描述
     */
    public $description;

    /**
     * 拍摄地点
     */
    public $location;

    /**
     * 薪酬/薪资要求：0为无薪酬，留空为不显示，非0为薪酬数值
     *
     */
    public $salary;

    /**
     * 经验年限：0为不限
     */
    public $experience;

    /**
     * 拍摄开始时间
     * @var
     */
    public $starttime;

    /**
     * 拍摄结束时间
     * @var
     */
    public $endtime;

    /** @var 附件 */
    public $attach;

    /**
     * 通告角色id
     * @var
     */
    public $role_ids;

    /**
     * @var Notice|null;
     */
    private $_model = null;

    private $_needs = [];
//
    /**
     * @var array 待添加的组图
     */
    private $_newPics = [];

    /**
     * @var array 待删除的组图
     */
    private $_deletePics = [];

    public function rules()
    {
        return [
            [['user_id', 'salary', 'experience', 'starttime', 'endtime'], 'integer'],
            [['title', 'description', 'starttime', 'endtime', 'location', 'salary', 'experience'], 'required'],
            [['title'], 'string', 'max' => 100],
            [['description'], 'string', 'max' => 255],
            [['location'], 'string', 'max' => 50],
            [['attach', 'role_ids'], 'safe'],
            [['notice_id'], 'validateNoticeId', 'skipOnEmpty' => false],
            [['user_id'], 'validateUser'],
            [['role_ids'], 'validateNeeds'],
            ['attach', 'validatePictures'],
            ['title', 'validateTitle'],
            ['description', 'validateDescription'],

        ];
    }

    public function validateUser($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        $uid = $this->$attribute;
        $user = User::find()->active()->andWhere([
            'id' => $uid,
        ])->one();
        if (!$user) {
            return $this->addError($attribute, '用户信息不存在或者当前用户被禁用');
        }
//        $notice = new Notice();
//        $notice->user_id = $user->id;
//        $this->_model = $notice;
    }

    public function validateNoticeId($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        $id = $this->$attribute;
        $this->_model = Notice::findOrNew($id);
    }

    public function validateNeeds($attribute)
    {
        if ($this->hasErrors() || !$this->$attribute) {
            return;
        }

//        $model = $this->model;

//        if ($model && $model->isNewRecord) {
//            return;
//        }
        $need_ids = explode(',', $this->$attribute);
        $this->_needs = array_filter($need_ids);
    }

    /**
     * 校验商品图集
     * @param string $attribute the attribute currently being validated
     */
    public function validatePictures($attribute)
    {
//        $model = $this->getModel();
//        $old = ArrayHelper::map($model->album, 'id', 'path');
//        $viaData = $this->divideViaData($old, $this->$attribute);
//        $this->_deletePics = ArrayHelper::getValue($viaData, 'remove', []);
//        $this->_newPics = ArrayHelper::getValue($viaData, 'create', []);
        if ($this->hasErrors() || !$this->$attribute) {
            return;
        }
        $attach_ids = explode(',', $this->$attribute);
        $this->_newPics = array_filter($attach_ids);
    }

    public function validateDescription($attribute)
    {
        if ($this->hasErrors() || !$this->$attribute) {
            return;
        }
        /* @var $wechat MpWechat */
        $wechat = Yii::$app->get('wechat');
        $return = $wechat->msgSecCheck($this->$attribute);
        if (is_array($return) && array_key_exists('code', $return) && array_key_exists('msg', $return) && $return['code'] == 87014) {
            $this->addError($attribute, $return['msg']);
        }
    }

    public function validateTitle($attribute)
    {
        if ($this->hasErrors() || !$this->$attribute) {
            return;
        }
        /* @var $wechat MpWechat */
        $wechat = Yii::$app->get('wechat');
        $return = $wechat->msgSecCheck($this->$attribute);
        if (is_array($return) && array_key_exists('code', $return) && array_key_exists('msg', $return) && $return['code'] == 87014) {
            $this->addError($attribute, $return['msg']);
        }
    }

    public function getModel()
    {
        return $this->_model;
    }

    public function save()
    {
        if (!$this->validate()) {
            $this->validateError('提交内容验证失败');
        }
        $model = $this->model;
        $model->setAttributes([
            'user_id' => $this->user_id,
            'title' => $this->title,
            'description' => $this->description,
            'starttime' => $this->starttime,
            'endtime' => $this->endtime,
            'location' => $this->location,
            'salary' => $this->salary,
            'experience' => $this->experience,
        ]);
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
//            $attachmodel = NoticeAttach::findOrNew([
//                'notice_id' => $model->id,
//            ]);
//            $attachmodel->setAttributes([
//                'path' => Url::attach($this->attach)
//            ]);
//            if (!$attachmodel->save()) {
//                throw new Exception($attachmodel->getErrorMsg());
//            }
            /*删除角色*/
            $roleids = $this->_needs;
            $hasneeds = NoticeNeed::find()->active()->andWhere(['notice_id' => $model->id])->all();
            foreach ($hasneeds as $need) {
                if (!$need->delete()) {
                    throw new Exception($need->getErrorMsg());
                }
            }
            /*插入角色*/
            $models = ShowbizRole::find()->active()->where(['in', 'id', $roleids])->all();
            foreach ($models as $itemmodel) {
                $needmodel = new NoticeNeed();
                $needmodel->setAttributes([
                    'notice_id' => $model->id,
                    'role_id' => $itemmodel->id,
                ]);
                if (!$needmodel->save()) {
                    throw new Exception($needmodel->getErrorMsg());
                }
            }

            /* 删除之前的图片 */
            $hasattachs = NoticeAttach::find()->active()->andWhere(['notice_id' => $model->id])->all();
            foreach ($hasattachs as $attach) {
                if (!$attach->delete()) {
                    throw new Exception($attach->getErrorMsg());
                }
            }
            /* 保存新图片 */
            if (!empty($this->_newPics)) {
                $album = new NoticeAttach();
                $album->attributes = [
                    'notice_id' => $model->id,
                ];
//                $i = 0;
                foreach ($this->_newPics as $index => $pic) {
                    $_album = clone $album;
                    $_album->attributes = [
                        'path' => $pic,
                    ];
//                    $_album->listorder = $i++;
                    if (!$_album->save()) {
                        throw new Exception($_album->getErrorMsg());
                    }
                }
            }
            //
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $model;
    }
}